package org.amos.core.frame.config.thread;

import cn.hutool.core.util.StrUtil;
import org.amos.core.frame.config.properties.AbstractThreadPoolProperties;
import org.amos.core.frame.config.properties.ThreadPoolProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;

public abstract class AbstractAsyncExecutor {
    @Autowired
    private ThreadPoolProperties threadPoolProperties;

    protected Executor init(AbstractThreadPoolProperties properties, RejectedExecutionHandler rejectedExecutionHandler) {
        //Java虚拟机可用的处理器数
        int processors = Runtime.getRuntime().availableProcessors();
        //定义线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(Objects.nonNull(properties.getCorePoolSize()) ? properties.getCorePoolSize() : processors);
        //线程池最大线程数,默认：40000
        executor.setMaxPoolSize(Objects.nonNull(properties.getMaxPoolSize()) ? properties.getMaxPoolSize() : 40000);
        //线程队列最大线程数,默认：80000
        executor.setQueueCapacity(Objects.nonNull(properties.getMaxPoolSize()) ? properties.getMaxPoolSize() : 80000);
        //线程名称前缀
        executor.setThreadNamePrefix(StrUtil.isNotEmpty(properties.getThreadNamePrefix()) ? properties.getThreadNamePrefix() : "amos-sync-thread-pool-");
        //线程池中线程最大空闲时间，默认：60，单位：秒
        executor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
        //核心线程是否允许超时，默认:false
        executor.setAllowCoreThreadTimeOut(threadPoolProperties.isAllowCoreThreadTimeOut());
        //IOC容器关闭时是否阻塞等待剩余的任务执行完成，默认:false（必须设置setAwaitTerminationSeconds）
        executor.setWaitForTasksToCompleteOnShutdown(threadPoolProperties.isWaitForTasksToCompleteOnShutdown());
        //阻塞IOC容器关闭的时间，默认：10秒（必须设置setWaitForTasksToCompleteOnShutdown）
        executor.setAwaitTerminationSeconds(threadPoolProperties.getAwaitTerminationSeconds());
        //拒绝策略，默认是AbortPolicy
        executor.setRejectedExecutionHandler(rejectedExecutionHandler);
        executor.setTaskDecorator(new MdcTaskDecorator());
        //初始化
        executor.initialize();

        return executor;
    }
}
